import * as request from '@/common/sju.request'
import * as appConfig from '@/config/config'
import * as jweixin from 'weixin-js-sdk'
import * as alert from '@/common/sju.alert.js'
import { t } from '@/common/sju.i18n.js'

// 微信JS-SDK配置常量
const WX_CONFIG = {
  debug: false,
  jsApiList: [
    'checkJsApi',
    'updateTimelineShareData',
    'updateAppMessageShareData',
    'hideMenuItems',
    'scanQRCode'
  ],
  hideMenuItems: [
    'menuItem:originPage',
    'menuItem:openWithSafari',
    'menuItem:openWithQQBrowser',
    'menuItem:editTag',
    'menuItem:copyUrl',
    'menuItem:share:qq',
    'menuItem:favorite',
    'menuItem:share:QZone',
    'menuItem:openWithSafari'
  ]
}

/**
 * 初始化微信JS-SDK配置
 * @param {Object} configData 微信配置数据
 * @returns {Promise<void>}
 */
async function initWXConfig(configData) {
  return new Promise((resolve, reject) => {
    jweixin.config({
      ...WX_CONFIG,
      appId: configData.appId,
      timestamp: configData.timestamp,
      nonceStr: configData.nonceStr,
      signature: configData.signature
    })

    jweixin.ready(() => {
      jweixin.hideMenuItems({ menuList: WX_CONFIG.hideMenuItems })
      resolve()
    })

    jweixin.error(err => {
      reject(new Error(t('common.weixin.init_fail', { msg: err.errMsg })))
    })
  })
}

/**
 * 微信分享配置
 * @param {string} title 分享标题
 * @param {string} linkUrl 分享链接
 * @param {string} imgUrl 分享图标
 * @param {string} desc 分享描述
 */
async function weixinJSConfig(title, linkUrl, imgUrl, desc) {
  try {
    const url = window.location.href
    const res = await request('/home/getWeixinJSConfig', 'post', { url })
    
    await initWXConfig(res.data)

    jweixin.ready(() => {
      // 分享到朋友圈
      jweixin.updateTimelineShareData({
        title,
        link: appConfig.appUrl + linkUrl,
        imgUrl,
        success: () => console.log('朋友圈分享设置成功')
      })

      // 分享给朋友
      jweixin.updateAppMessageShareData({
        title,
        desc,
        link: appConfig.appUrl + linkUrl,
        imgUrl,
        success: () => console.log('朋友分享设置成功')
      })
    })

  } catch (error) {
    alert.showError(t('common.weixin.share_fail', { msg: error.message }))
  }
}

/**
 * 微信扫码功能
 * @returns {Promise<string>} 扫码结果
 */
async function scanQRCode() {
  try {
    const url = window.location.href
    const res = await request('/home/getWeixinJSConfig', 'post', { url })
    
    await initWXConfig(res.data)

    return new Promise((resolve, reject) => {
      jweixin.scanQRCode({
        needResult: 1,
        scanType: ['qrCode', 'barCode'],
        success: res => {
          const result = processScanResult(res.resultStr)
          resolve(result)
        },
        fail: err => reject(new Error(t('common.weixin.scan_error', { msg: err.errMsg })))
      })
    })

  } catch (error) {
    alert.showError(t('common.weixin.scan_fail', { msg: error.message }))
    throw error
  }
}

/**
 * 处理扫码结果
 * @param {string} resultStr 原始扫码结果
 * @returns {string} 处理后的结果
 */
function processScanResult(resultStr) {
  if (resultStr.includes(',')) {
    // 条形码处理
    const code = resultStr.split(',')[1]
    return code.replace(/[^a-z\d]/ig, '').replace('sn', '')
  }
  // 二维码直接返回
  return resultStr
}

export {
  weixinJSConfig,
  scanQRCode
}